﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WJ.Infrastructure.Serializer
{
    public static class ObjectExtension
    {
        #region 序列化为二进制

        ///   <summary>   
        ///   序列化位二进制   
        ///   </summary>   
        ///   <param   name="request">要序列化的对象</param>   
        ///   <returns>字节数组</returns>   
        public static byte[] SerializeBinary(this object request)
        {
            using (MemoryStream memStream = new MemoryStream())
            {
                BinaryFormatter serializer = new BinaryFormatter();
                serializer.Serialize(memStream, request);
                return memStream.GetBuffer();
            }
        }

        #endregion

        #region 二进制反序列化

        ///   <summary>   
        ///   二进制反序列化   
        ///   </summary>   
        ///   <param   name="buf">字节数组</param>   
        ///   <returns>得到的对象</returns>   
        public static object DeserializeBinary(this byte[] buf)
        {
            if (buf == null)
            {
                return null;
            }
            using (MemoryStream memStream = new MemoryStream(buf))
            {
                memStream.Position = 0;
                BinaryFormatter deserializer = new BinaryFormatter();
                object info = (object) deserializer.Deserialize(memStream);
                memStream.Close();
                return info;
            }
        }

        #endregion

        #region Json序列化

        /// <summary>
        /// Json序列化
        /// </summary>
        public static string ToJson(this object item)
        {
            using (StringWriter sw = new StringWriter())
            {
                JsonSerializer serializer = JsonSerializer.Create(
                    new JsonSerializerSettings
                    {
                        DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,

                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    }
                );
                serializer.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                
                JsonWriter jsonWriter = new JsonTextWriter(sw)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                
                using (jsonWriter)
                {
                    serializer.Serialize(jsonWriter, item);
                }
                return sw.ToString();
            }
        }
        
        

        #endregion

        #region Json反序列化

        /// <summary>
        /// Json反序列化
        /// </summary>
        public static T FromJsonTo<T>(this string jsonString) where T : class, new()
        {
            T t = JsonConvert.DeserializeObject<T>(jsonString);

            return t;
        }

        public static T FromJsonToOrDefault<T>(this string str) where T : class, new()
        {
            if (string.IsNullOrEmpty(str) || str == "[]" || str == "{}")
            {
                return new T();
            }
            else
            {
                return JsonConvert.DeserializeObject<T>(str);
            }
        }

        #endregion
    }
}